
import { createRouter, createWebHistory } from "vue-router";

import {useToken} from "@/untils/token.js"

// 1. 配置路由
const routes = [
    {
        path: "/", // 默认路由 home页面
        redirect: "/login",
    },
    {
        path: "/login", // 默认路由 home页面
        component: () => import("@/pages/login/login.vue"),
        name: "login",
        title: "登录"
    },
    {
        path: "/home", // 默认路由 home页面
        component: () => import("@/pages/layout/layout.vue"),
        name: "home",
        title: "首页"
    },
    {
        path: "/user", // 默认路由 home页面
        component: () => import("@/pages/userPage/userList.vue"),
        name: "user",
        title: "用户维护"
    }
];

// 2.返回一个 router 实列，为函数，配置 history 模式
const router = createRouter({
    history: createWebHistory(),
    routes,
});

//路由拦截器 进行token的判断  如果没有token就跳转到登录页面
router.beforeEach((to,from,next)=>{
    if(to.path === '/login'){
        next()
    }else{
        let token = useToken().getToken()
        if(token){
            next()
        }else{
            next({ path: '/' , query: { redirect: to.fullPath } })
        }
    }
})
router.beforeEach((to,from,next)=>{
    next()
})

export default router